<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <pageTools>
        <template v-slot:left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <template #right>
          <el-button type="primary" @click="$router.push('/import?type=user')">导入</el-button>
          <el-button type="success" @click="handleDownload">导出</el-button>
          <el-button type="warning" @click="showDialog = true">添加员工</el-button>
        </template>
      </pageTools>
      <!-- 员工表格 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="employeeList">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template v-slot="{row}">
              <img
                v-imageer="defaultImg"
                :src="row.staffPhoto || defaultImg"
                alt=""
                style="width:70px; height: 70px;border-radius: 50%;"
                @click="showEwm(row.staffPhoto)"
              >
              <!-- <p>{{ row }}</p> -->
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" :formatter="formatterEmployment" prop="formOfEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{row}">
              {{ row.timeOfEntry |formatDate('YYYY-MM-DD') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button v-if="power('SELECT_LOOK')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="AssignRole(row.id)">角色</el-button>
              <el-button v-if="power('SELECT_DEL')" type="text" size="small" @click="delCurrentList(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :current-page="page"
            :page-size="pagesize"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <el-dialog title="二维码" :visible.sync="showEwmDialog" style="text-align:center;" width="300px">
      <!-- <el-row type="flex" justify="center"> -->
      <canvas ref="canvs" />
      <!-- </el-row> -->
    </el-dialog>
    <!-- 新增员工 -->
    <AddEmployee :show-dialog.sync="showDialog" />
    <!-- 分配角色 -->
    <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import AssignRole from './components/assign-role.vue'
import qrCode from 'qrcode'
import defaultImg from '@/assets/common/head.jpg'
import AddEmployee from '@/views/employees/components/add-employee.vue'
import Empolayment from '@/api/constant/employees'
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      showDialog: false,
      page: 1, // 当前页
      pagesize: 10, // 每页条数
      employeeList: [],
      total: 0,
      defaultImg,
      showEwmDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.EmployeeList()
  },
  methods: {
    power(info) {
      let res = 0
      if (this.$store.getters.power.points.length !== 0) {
        res = this.$store.getters.power.points
      } else {
        return false
      }
      if (res.includes(info)) {
        return true
      } else {
        return false
      }
    },
    async EmployeeList() {
      const { data: { rows, total }} = await reqGetEmployeeList(this.page, this.pagesize)
      this.employeeList = rows
      this.total = total
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.EmployeeList()
    },
    // 聘用形式的处理函数
    formatterEmployment(row, column, cellValue, index) {
      const { hireType } = Empolayment
      const result = hireType.find(item => item.id === cellValue * 1)
      return result ? result.value : '未知'
    },
    // 删除当前条数据
    async delCurrentList(id) {
      if (this.employeeList.length === 1 && this.page > 1) {
        this.page--
      }
      await reqDelEmployee(id)
      this.EmployeeList()
    },
    // 点击的导出按钮
    async  handleDownload() {
      // 表头
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      // console.log(rows)

      const newArr = []
      rows.forEach(item => {
        const arr = []
        headersArr.forEach(value => {
          const englishKey = headersRelations[value]
          if (englishKey === 'formOfEmployment') {
            const obj = Empolayment.hireType.find(v => v.id === item[englishKey])
            const res = obj ? obj.value : '未知'
            arr.push(res)
          } else {
            arr.push(item[englishKey])
          }
        })
        newArr.push(arr)
      })
      // console.log(newArr)
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr,
          data: newArr,
          filename: '表格',
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader,
          merges
        })
      })
    },
    // 二维码dialog显示与隐藏
    showEwm(url) {
      if (!url) return
      this.showEwmDialog = true
      this.$nextTick(() => {
        qrCode.toCanvas(this.$refs.canvs, url)
      })
    },
    AssignRole(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }
}

</script>

<style>

</style>
